<template>
  <view class="container">
    <!-- 页面头部标题 -->
    <view class="page-header" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="header-content" :style="{ height: navBarHeight + 'px' }">
        <view class="header-title" :style="{ lineHeight: navBarHeight + 'px' }">皓祺智陪</view>
      </view>
    </view>

    <!-- 主要功能卡片 -->
    <view class="main-card">
      <!-- 轮播图 -->
      <view class="banner-section">
        <swiper class="banner-swiper" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="500"
          indicator-color="rgba(255,255,255,0.5)" indicator-active-color="#ffffff" circular>
          <swiper-item v-for="(item, index) in bannerList" :key="index">
            <view class="banner-item">
              <image class="banner-image" :src="item.image" mode="aspectFill"></image>
            </view>
          </swiper-item>
        </swiper>
      </view>

      <!-- 主要功能按钮 -->
      <view class="main-actions">
        <!-- 扫码按钮组 - 上下排列 -->
        <view class="action-buttons">
          <view class="action-btn rental-btn" @click="handleScanRental">
            <view class="btn-text">扫码租用</view>
          </view>
          <view class="action-btn return-btn" @click="handleScanReturn">
            <view class="btn-text">扫码归还</view>
          </view>
        </view>

        <!-- 三个功能按钮 -->
        <view class="feature-buttons">
          <view class="feature-btn" @click="handleBluetooth">
            <view class="feature-icon bluetooth-icon">
              <img style="width: 48px; height: 48px" src="/static/new/lanya.png" alt="" srcset="" />
            </view>
            <view class="feature-text">蓝牙授权</view>
          </view>
          <view class="feature-btn" @click="handleGuide">
            <view class="feature-icon guide-icon">
              <img style="width: 48px; height: 48px" src="/static/new/caozuozhinan.png" alt="" srcset="" />
            </view>
            <view class="feature-text">操作指南</view>
          </view>
          <view class="feature-btn" @click="handleContact">
            <view class="feature-icon contact-icon">
              <img style="width: 48px; height: 48px" src="/static/new/phone.png" alt="" srcset="" />
            </view>
            <view class="feature-text">联系客服</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 更多服务 -->
    <view class="more-services" v-if="isAdmin">
      <view class="services-title">更多服务</view>
      <view class="services-grid">
        <view class="service-item" v-for="(item, index) in serviceList" :key="index" @click="handleMoreService(item)">
          <view class="service-icon" v-if="item.icon">
            <u-icon :name="item.icon" size="60" color="#87ceeb"></u-icon>

          </view>
          <image v-else :src="item.image" mode="scaleToFill" style="width: 106rpx; height: 106rpx;" />
          <view class="service-text">{{ item.name }}</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getArticle, getOrderDetailByDeviceId } from "@/api/index.js";
import navbarMixin from "@/common/mixin/navbar.js";
import { getBanners, isAdmin as getUserIsAdmin } from "@/api/index.js";
import Config from "@/core/config";

// 后端api地址
const apiUrl = Config.get("apiUrl");

export default {
  mixins: [navbarMixin],

  data() {
    return {
      // 轮播图数据
      bannerList: [],
      // 更多服务数据
      serviceList: [
        { id: 1, icon: "setting", name: "管理员入口" },
        { id: 2, name: "敬请期待", image: "/static/common/1.png" },
        { id: 3, name: "敬请期待", image: "/static/common/2.png" },
        { id: 4, name: "敬请期待", image: "/static/common/3.png" },
        { id: 4, name: "敬请期待", image: "/static/common/4.png" }
      ],

      isAdmin: false,
      phone: "",
    };
  },
  async onLoad(options) {

    await getArticle({ id: 15 }).then((res) => {
      // this.phone = res.content;
      // res.content<p>123</p>，我想提取出中间的数字
      this.phone = res.content.match(/[0-9]{11}/)[0];
    });

    const systemInfo = uni.getSystemInfoSync();
    console.log('systemInfo', systemInfo);

  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onShow(options) {
    // 根据医院加载不同轮播图
    this.loadHospitalBanner();
    // 判断当前用户是否管理员
    const _res = await getUserIsAdmin();



    this.isAdmin = _res.modules.length > 0;





    // wx.requestMerchantTransfer({
    //   mchId: '1721801946',
    //   appId: wx.getAccountInfoSync().miniProgram.appId,
    //   package: 'ABBQO+oYAAABAAAAAADgrMxf7rSmru4S5UzeaBAAAADnGpepZahT9IkJjn90+1qgDE2MAeqCz9opp+JRYSOCXNdhqaqJ3G7z+GSGRJQDRQkUAMkJJE2NB4pxwoor519SjXv4Q3U1fx4SXgD33YzjS2XeO+I=',
    //   success: (res) => {
    //     // res.err_msg将在页面展示成功后返回应用时返回ok，并不代表付款成功
    //     console.log('success:', res);
    //   },
    //   fail: (res) => {
    //     console.log('fail:', res);
    //   },
    // });
  },

  methods: {
    startDiscovery() {
      uni.startBluetoothDevicesDiscovery({
        services: ["0000feef-0000-1000-8000-00805f9b34fb"],
        success: (res) => {
          console.log("resresres", res);

          uni.onBluetoothDeviceFound((found) => {
            const device = found.devices[0];
            if (
              device.advertisData &&
              this.checkLockProtocol(device.advertisData)
            ) {
              this.connectDevice(device.deviceId);
            }
          });
        },
      });
    },
    /**
     * 根据医院加载轮播图
     */
    async loadHospitalBanner() {
      // 这里可以根据用户所在医院动态加载不同的轮播图
      // 暂时使用静态数据
      try {
        this.bannerList.length = 0;
        const data = await getBanners();

        data?.forEach((_d) => {
          this.bannerList.push({
            ..._d,
            image: apiUrl + _d.image,
          });
        });
      } catch (error) {
        console.log("errorerrorerror", error);
      }
    },

    /**
     * 扫码租用
     */
    handleScanRental() {

      const app = this;

      // 检查是否登陆了
      if (!uni.getStorageSync("token")) {
        uni.showModal({
          title: "提示",
          content: "请先登陆",
          success: function (res) {
            if (res.confirm) {
              uni.navigateTo({
                url: "/pages/login/index",
              });
            } else if (res.cancel) {
              return;
            }
          },
        });
        return;
      }

      uni.scanCode({
        scanType: ["qrCode", "barCode"],
        success(res) {
          console.log('res?.result', res?.result);

          return uni.navigateTo({
            url: `/pages/newpayment/index?code=${encodeURIComponent(
              // this.scanResult/
              res?.result?.split("kpl/")?.[1]
            )}&type=rental`,
          });
        },
        fail(err) {
          console.log('err', err);

          if (err.errMsg.includes("cancel")) {
            return;
          }
          uni.showToast({
            title: "扫码失败，请重试",
            icon: "none",
          });
        },
      });
      // this.checkBluetoothPermission();
    },

    /**
     * 扫码归还
     */
    async handleScanReturn() {
      const app = this;



      // 检查是否登陆了
      if (!uni.getStorageSync("token")) {
        uni.showModal({
          title: "提示",
          content: "请先登陆",
          success: function (res) {
            if (res.confirm) {
              uni.navigateTo({
                url: "/pages/login/index",
              });
            } else if (res.cancel) {
              return;
            }
          },
        });
        return;
      }

      uni.showLoading({
        title: '加载中',
        mask: true
      })



      uni.scanCode({
        scanType: ["qrCode", "barCode"],
        async success(res) {

          try {
            const _res = await getOrderDetailByDeviceId({
              equipment_info_id: encodeURIComponent(
                res?.result?.split("kpl/")?.[1])
            })

            console.log('获取到订单信息', _res);

            return uni.navigateTo({
              url: `/pages/newreturn/index?code=${_res?.id}&type=return`,
            });
          } catch (error) {
            uni.hideLoading();

            uni.showToast({
              title: error?.msg,
              icon: "none",
            });

            console.log('errorerrorerror', error);

          }


        },
        fail(err) {
          if (err.errMsg.includes("cancel")) {
            return;
          }
          uni.showToast({
            title: "扫码失败，请重试",
            icon: "none",
          });
        },
      });
    },

    /**
     * 蓝牙授权
     */
    handleBluetooth() {
      uni.navigateTo({
        url: "/pages/newbluetooth/index",
      });
    },

    /**
     * 操作指南
     */
    handleGuide() {
      uni.navigateTo({
        url: "/pages/newguide/index",
      });
    },

    /**
     * 联系客服
     */
    handleContact() {
      // 弹出拨打电话的选择
      uni.showActionSheet({
        title: "皓祺智陪",
        itemList: [`呼叫 ${this.phone}`],
        success: (res) => {
          if (res.tapIndex === 0) {
            // 拨打电话
            uni.makePhoneCall({
              phoneNumber: this.phone,
              success: () => {
                console.log("呼叫成功");
              },
              fail: () => {
                uni.showToast({
                  title: "呼叫失败",
                  icon: "none",
                });
              },
            });
          }
        },
      });
    },

    /**
     * 更多服务点击
     */
    handleMoreService(data) {
      if (data.id == 1) {
        uni.navigateTo({
          url: "/pages/adminPage/index",
        });
      } else {
        uni.showToast({
          title: "敬请期待",
          icon: "none",
        });
      }

    },

    // 检查蓝牙权限
    checkBluetoothPermission() {
      uni.getSetting({
        success(res) {
          if (res.authSetting["scope.bluetooth"]) {
            console.log("已授权蓝牙");
            uni.navigateTo({
              url: "/pages/newscan/index?type=rental",
            });
          } else {
            console.log("未授权蓝牙");
            uni.authorize({
              scope: "scope.bluetooth",
              success() {
                console.log("授权成功");
                uni.navigateTo({
                  url: "/pages/newscan/index?type=rental",
                });
              },
              fail() {
                uni.showModal({
                  title: "提示",
                  content: "需要蓝牙权限才能使用该功能",
                  showCancel: false,
                });
              },
            });
          }
        },
      });
    },
  },

  /**
   * 分享当前页面
   */
  onShareAppMessage() {
    return {
      title: "皓祺智陪",
      path: "/pages/newindex/index",
    };
  },
};
</script>
<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #ffffff;
  padding-bottom: 120rpx;
  position: relative;

  // 顶部半圆形蓝色背景
  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 350rpx;
    background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
    border-radius: 0 0 30% 30%;
    z-index: 0;
  }
}

.page-header {
  position: relative;
  z-index: 1;

  .header-content {
    display: flex;
    align-items: center;
    padding: 0 40rpx;

    .header-title {
      font-size: 48rpx;
      font-weight: bold;
      color: #ffffff;
      text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    }
  }
}

// 主要功能卡片容器
.main-card {
  margin: 20rpx 30rpx 40rpx;
  background: #ffffff;
  border-radius: 24rpx;
  padding: 30rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
}

.banner-section {
  margin-bottom: 30rpx;
  border-radius: 24rpx;
  overflow: hidden;

  .banner-swiper {
    height: 440rpx; // 增加轮播图高度

    .banner-item {
      width: 100%;
      height: 100%;

      .banner-image {
        width: 100%;
        height: 100%;
        background: rgb(108, 108, 108);
        display: flex;
        align-items: center;
        justify-content: center;
        color: #999;
        font-size: 28rpx;
      }
    }
  }
}

.main-actions {
  .action-buttons {
    display: flex;
    flex-direction: column; // 改为上下排列
    gap: 20rpx;
    margin-bottom: 40rpx;

    .action-btn {
      width: 100%; // 全宽，和轮播图一致
      height: 100rpx;
      border-radius: 50rpx; // 增大圆角
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15); // 增强阴影
      position: relative;
      overflow: hidden;

      // 添加光泽效果
      &::after {
        content: "";
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg,
            transparent,
            rgba(255, 255, 255, 0.3),
            transparent);
        transition: left 0.6s;
      }

      &:active::after {
        left: 100%;
      }

      .btn-text {
        font-size: 32rpx;
        font-weight: 600;
        color: #ffffff;
        text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
        z-index: 1;
        position: relative;
      }

      &.rental-btn {
        background: linear-gradient(135deg, #00b894 0%, #00a085 100%);
        box-shadow: 0 8rpx 24rpx rgba(0, 184, 148, 0.4); // 绿色阴影

        &:active {
          transform: translateY(2rpx);
          box-shadow: 0 6rpx 20rpx rgba(0, 184, 148, 0.5);
        }
      }

      &.return-btn {
        background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
        box-shadow: 0 8rpx 24rpx rgba(116, 185, 255, 0.4); // 蓝色阴影

        &:active {
          transform: translateY(2rpx);
          box-shadow: 0 6rpx 20rpx rgba(116, 185, 255, 0.5);
        }
      }
    }
  }

  .feature-buttons {
    display: flex;
    justify-content: space-around;

    .feature-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20rpx;

      .feature-icon {
        width: 96rpx;
        height: 96rpx;
        background: rgba(116, 185, 255, 0.1);
        border-radius: 24rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 16rpx;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
      }

      .feature-text {
        font-size: 24rpx;
        color: #666666;
        text-align: center;
      }
    }
  }
}

.more-services {
  margin: 0 30rpx;
  background: #ffffff;
  border-radius: 24rpx;
  padding: 40rpx 30rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;

  .services-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333333;
    margin-bottom: 30rpx;
  }

  .services-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 40rpx;
    justify-content: space-between;
    // justify-content: space-around;

    .service-item {
      display: flex;
      flex-direction: column;
      width: 120rpx;
      justify-content: center;
      align-items: center;

      .service-icon {
        width: 96rpx;
        height: 96rpx;
        background: #f8f9fa;
        border: 2rpx solid #e9ecef;
        border-radius: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 16rpx;
      }

      .service-text {
        font-size: 24rpx;
        color: #666666;
        text-align: center;
      }
    }
  }
}
</style>
